package com.task.mall.controller.admin;

import com.google.gson.Gson;
import com.task.mall.bean.Msg;
import com.task.mall.bean.Result;
import com.task.mall.service.Msgservice;
import com.task.mall.service.Orderservice;
import com.task.mall.service.impl.MsgServiceImpl;
import com.task.mall.service.impl.OrderserviceImpl;
import com.task.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

@WebServlet("/api/admin/msg/*")
public class MsgServlet extends HttpServlet {
    Msgservice msgService = new MsgServiceImpl();
    Gson gson = new Gson();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/msg/", "");
        if ("reply".equals(action)){
            reply(request,response);
        }
    }

    /**
     * 进行回复
     * @param request
     * @param response
     */
    private void reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Msg msg = gson.fromJson(requestBody, Msg.class);
        int result = msgService.reply(msg);
        Result res = new Result();
        if (result == 200){
            res.setCode(0);
        }
        response.getWriter().println(gson.toJson(res));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/msg/", "");
        if ("noReplyMsg".equals(action)){
            noReplyMsg(request,response);
        }else if ("repliedMsg".equals(action)){
            repliedMsg(request,response);
        }
    }

    /**
     * 显示已回复的留言板
     * @param request
     * @param response
     */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Msg> msg = msgService.repliedMsg();
        Result res = new Result();
        res.setCode(0);
        res.setData(msg);
        response.getWriter().println(gson.toJson(res));
    }

    /**
     * 显示未回复留言板
     * @param request
     * @param response
     */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Msg> msg = msgService.noReplyMsg();
        Result res = new Result();
        res.setCode(0);
        res.setData(msg);
        response.getWriter().println(gson.toJson(res));
    }
}
